import $store from '../store'
let socket
export function socketConnect() {
  // 建立websocket连接
  socket = new WebSocket('ws://localhost:9090/socket/'.concat($store.state.user.userInfo.id))
  socket.onopen = function() {
    console.log('websocket已经打开')
  }
  socket.onerror = function() {
    alert('网络已断开')
  }
  socket.onclose = function() {
    alert('网络已断开')
  }
  // 获取信息
  socket.onmessage = function(res) {
    const data = JSON.parse(res.data)
    // console.log(data)
    switch (data.type) {
      // eslint-disable-next-line no-case-declarations
      case 'message':
        const content = data.content
        // 分发数据
        if (content.consultationId === $store.state.user.chattingId) {
          $store.dispatch('pushMessage', content)
        }
        break
      // 提交数据id
      case 'check':
        $store.commit('SET_CHECK_ID', data.content.messageID)
        break
      // 在线用户管理，避免同时登录同一用户
      case 'kick':
        alert(data.content)
        socket.close()
        $store.dispatch('FedLogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
        break
      default:
        console.log(data)
    }
  }
}
// 发送信息
export function sendMessage(type, content) {
  const message = {
    type: type,
    content: content
  }
  socket.send(JSON.stringify(message))
}
